import config from '@/config';
import { message } from 'ant-design-vue';
import { boxPrintSuccess } from '@/api/base/box_data.js';
import { samplePrintSuccess } from '@/api/store/sample_data.js';
import { printSingleSelect } from '@/api/store/single_data.js';

/**
 * 打印试管盒
 * boxs为数组，每个对象应该包含试管盒的全部信息：serial、epc
 */
export const printBoxs = (boxs) => {
  console.log('打印试管盒:', boxs);
  if (!boxs || boxs.length == 0) {
    message.error('缺少待打印的试管盒数据');
  }
  const printData = boxs.map((item) => {
    return { epc: item.epc, serial: item.serial };
  });
  const callback = () => {
    printBoxSuccess(boxs);
  };
  print('Templates\\国家疾控-试管盒.btw', printData, callback);
};

/**
 * 打印试管盒
 * boxs为数组，每个对象应该包含试管盒的全部信息：serial、epc
 */
export const printSpecimens = (specimens) => {
  console.log('打印暂存样本:', specimens);
  if (!specimens || specimens.length == 0) {
    message.error('缺少待打印的暂存样本数据');
  }
  expandExtDataList(specimens);
  const callback = () => {
    samplePrintSuccess({ specimenList: specimens });
  };
  print(`Templates\\国家疾控-暂存试管.btw`, specimens, callback);
};

/**
 * 打印试管
 */
export const printStrains = (strains) => {
  console.log('打印试管:', strains);
  if (!strains || strains.length == 0) {
    message.error(`缺少待打印的试管数据`);
  }
  const callback = () => {
    printSingleSelect({ instances: strains });
  };
  print(`Templates\\国家疾控-试管.btw`, strains, callback);
};

const print = (templateName, printData, callback) => {
  // printSign 1开启 2不开启(用户测试)
  if (config.printSign === 1) {
    if (window.getPluginObject) {
      // 存在getPluginObject函数，表示js代码正在HCBrowser中运行
      let printer = getPluginObject('HC.Plugin.Print.LabelPrinter');
      if (printData.length > 0) {
        printer
          .PrintLabelList(templateName, printData, null, 1)
          .then(function (res) {
            console.log('打印结果：', res);
            if (res.code === 200) {
              callback();
              message.success('打印成功');
            } else {
              message.error('打印失败');
            }
          })
          .catch(function (reason) {
            message.error('打印失败');
          });
      }
    } else {
      message.info('浏览器不支持，请使用HCBrowser浏览此网页');
      return;
    }
  } else {
    callback();
    message.success('打印成功');
  }
};

function printBoxSuccess(boxs) {
  return boxPrintSuccess({ instances: boxs }).then((res) => {});
}

// 对于自定义字段需要展开，否则xml文件中无法直接显示
function expandExtDataList(list) {
  if (list) {
    list.forEach((element) => {
      if (element.extDataList) {
        element.extDataList.forEach((ext) => {
          element[ext.key] = ext.value;
        });
        element.extDataList = undefined;
      }
    });
  }
}
